package edu.xidian.cnmano.cronjob;

import edu.xidian.cnmano.entities.monitor.DeploymentInfo;
import edu.xidian.cnmano.entities.monitor.PodInfo;
import edu.xidian.cnmano.service.DeploymentInfoService;
import edu.xidian.cnmano.service.PodInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhr 有关于DeploymentInfo相关的定时任务，主要是定时访问数据库，统计一个deployment下面的pod申请和占用的所有资源
 * @date 2020/11/28-15:09
 */
@Component
@Slf4j
public class DeploymentInfoCronJob {

    @Resource
    private PodInfoService podInfoService;

    @Resource
    private DeploymentInfoService deploymentInfoService;

    @Scheduled(cron = "0/10 * * * * ?")
    public void updateOrInsertDeploymentInfo() {
        List<DeploymentInfo> deploymentInfoList = deploymentInfoService.listAllDeploymentInfo();
        //log.info("deploymentInfo update/insert cronjob running");
        try {
            for (DeploymentInfo deploymentInfo : deploymentInfoList) {
                String deploymentName = deploymentInfo.getDeploymentName();
                String namespace = deploymentInfo.getNamespace();
                List<PodInfo> podInfoList = podInfoService.listPodInfoByDeploymentNameAndNamespace(deploymentName, namespace);
                int totalCpuUsage = 0;
                int totalMemoryUsage = 0;
                int totalCpuRequest = 0;
                int totalMemoryRequest = 0;
                for (PodInfo podInfo : podInfoList) {
                    if (podInfo.getCpuRequest() != null) {
                        totalCpuRequest += podInfo.getCpuRequest();
                    }
                    if (podInfo.getMemoryRequest() != null) {
                        totalMemoryRequest += podInfo.getMemoryRequest();
                    }
                    if(podInfo.getCpuUsage()!=null){
                        totalCpuUsage += podInfo.getCpuUsage();
                    }
                    if(podInfo.getMemoryUsage()!=null){
                        totalMemoryUsage += podInfo.getMemoryUsage();
                    }
                }
                deploymentInfo.setTotalCpuRequest(totalCpuRequest);
                deploymentInfo.setTotalMemoryRequest(totalMemoryRequest);
                deploymentInfo.setTotalCpuUsage(totalCpuUsage);
                deploymentInfo.setTotalMemoryUsage(totalMemoryUsage);
                deploymentInfoService.updateDeploymentInfo(deploymentInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
